package com.rtx.wms.std.storer.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.rtx.wms.std.ctclass.ClassHolder;
import com.rtx.wms.std.sku.bean.po.Sku;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.rtx.common.HttpServletRequestUtil;
import com.rtx.model.dto.edi.EdiInnerRequestDTO;
import com.rtx.wms.std.common.bean.Storer;
import com.rtx.wms.std.qm.bean.RtxQMResponse;
import com.rtx.wms.std.storer.service.StorerService;

import io.swagger.annotations.Api;

@Api(tags = {"贸易伙伴"})
@RestController
@RequestMapping("/storer")
public class StorerController {
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	StorerService storerService;
	

	@PostMapping(value = "create")
	public String skuCreate(HttpServletRequest request) {
		RtxQMResponse res = new RtxQMResponse();
		try {
			String requestStr = HttpServletRequestUtil.getHttpBody(request);
    		EdiInnerRequestDTO requestDTO = JSON.parseObject(requestStr, EdiInnerRequestDTO.class);
    		
			Storer dto = addExternalColumns(requestDTO.getTagetjson(),requestDTO);
			
			storerService.addAndUpdataStorer("enterprise", dto);
			
			res.setSuccess("success");
		} catch (Exception e) {
			log.error("贸易伙伴创建异常-",e);
			res.setFailure(e.getMessage());
		}

		return JSON.toJSONString(res);
	}

	private Storer addExternalColumns(String tagetjson, EdiInnerRequestDTO dto) {
		Storer head = null;
		try {
			String apiid =  dto.getConfig().getTargetApi().getId()+"";
			Map<String,Class> map = ClassHolder.apiconfigClassMap.get(apiid);

			if(map != null && map.get("main") != null) {
				Class headclass =map.get("main");
				head =  (Storer) JSON.parseObject(tagetjson,headclass);
			}else {
				head = JSON.parseObject(tagetjson,Storer.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return head;
	}
}
